package com.itany.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.itany.conf.WebSocketServer;
import com.itany.order.service.IRoderService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;


@Controller
@RequestMapping("/testorder")
public class TestOrderController {

    @Reference
    private IRoderService roderService;

    @RequestMapping("/createImg")
    public void createImg(HttpServletResponse responses)throws Exception{
         responses.setHeader("Pragma","No-cache");
         responses.setContentType("image/jpeg");
         //获取二维码
         String qrCode = roderService.getQrCode();
         //生成二维码
         Map<EncodeHintType,Object> map = new HashMap<EncodeHintType,Object>();
         map.put(EncodeHintType.CHARACTER_SET,"UTF-8");
         BitMatrix bitMatrix = new MultiFormatWriter().encode(qrCode, BarcodeFormat.QR_CODE,200,200,map);
         MatrixToImageWriter.writeToStream(bitMatrix,"jpeg",responses.getOutputStream());
        responses.getOutputStream().flush();
        responses.getOutputStream().close();
    }

    @RequestMapping("/paySuccess/{no}")
    @ResponseBody
    public String paySuccess(@PathVariable("no") String no)throws Exception{
        System.out.println("执行到了回调方法，no = [" + no + "]");
        CopyOnWriteArraySet<WebSocketServer> servers = WebSocketServer.servers;
        for (WebSocketServer server: servers){
             if("1".equals(server.getUserId())){
                 server.getSession().getBasicRemote().sendText("1");
             }
        }
        return "success";
    }

}
